﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Windows.Controls;
using BaocaoNPC.common;
using Component;
using CMISLibrary;
//using busBaoCao;
using CMISLibrary.Libraries;
using System.IO;
using Microsoft.VisualBasic;
using BaocaoNPC.Usercontrols.reports;
using Ionic.Zip;
using bus_TienichNPC;

namespace BaocaoNPC.Usercontrols
{
    /// <summary>
    /// Interaction logic for ChamNoTheoFile.xaml
    /// </summary>
    public partial class ChamNoTheoFile : UserControl
    {
        #region Khai báo biến
        public String strMa_dviqly = NPCUS_DanhMuc.Pglobal.strMa_dviqly != "" && NPCUS_DanhMuc.Pglobal.strMa_dviqly != null ? NPCUS_DanhMuc.Pglobal.strMa_dviqly : "PA";
        public String strTenDNHap = NPCUS_DanhMuc.Pglobal.strTen_dangnhap != "" && NPCUS_DanhMuc.Pglobal.strTen_dangnhap != null ? NPCUS_DanhMuc.Pglobal.strTen_dangnhap : "PA";
        public String strTen_dviqly = NPCUS_DanhMuc.Pglobal.strTen_dviqly != "" && NPCUS_DanhMuc.Pglobal.strTen_dviqly != null ? NPCUS_DanhMuc.Pglobal.strTen_dviqly : "cty..";
        public String strTen_dviqly_CT = NPCUS_DanhMuc.Pglobal.strTen_dviqly_CT != "" && NPCUS_DanhMuc.Pglobal.strTen_dviqly_CT != null ? NPCUS_DanhMuc.Pglobal.strTen_dviqly_CT : "cap tren";
        public String strMa_TNgan = NPCUS_DanhMuc.Pglobal.strTen_dangnhap != "" && NPCUS_DanhMuc.Pglobal.strTen_dangnhap != null ? NPCUS_DanhMuc.Pglobal.strTen_dangnhap.ToUpper() : "PA";
        string pfile = "";
        string maloi = "";
        DataTable dt_ReadFileExcel = new DataTable();
        DataSet ds_CAPNHAT = new BCNPCEntities.EXCEL.ds_CAPNHAT();
        DataSet dsCNfile = new BCNPCEntities.EXCEL.dsCNFileExcel(); 
        //cls_ImportExcel_bus cls = new cls_ImportExcel_bus();
        int thang = 0, nam = 0;
        DataSet dsThuNganVien = new DataSet();
        string check_cham = "";
        #endregion
        public ChamNoTheoFile()
        {
            InitializeComponent();
            
        }

        private void btnDuongdan_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.OpenFileDialog fld = new System.Windows.Forms.OpenFileDialog();
            fld.Title = "Chọn file cập nhật chấm nợ";
            fld.Filter = "Excel Files(*.xls)|*.xls";
            try
            {
                if (fld.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    txtDuongDan.Text = fld.FileName.ToString();
                }
                if (txtDuongDan.Text.Length > 0)
                {
                    string[] filenames = txtDuongDan.Text.Split('\\');
                    foreach (string sfilename in filenames)
                    {
                        if (sfilename.Contains(".xls"))
                            pfile = sfilename.Substring(0, sfilename.Length - 4);
                    }
                }
            }
            catch
            {
                //fld.SelectedPath = "My Computer";
            }
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            BaocaoNPC.common.GlobalServices.Service_NPCUS.select_THANGNAMCONGNO(strMa_dviqly, ref thang, ref nam);
            lblthangnam.Content = "Tháng năm công nợ: " + thang.ToString() + "/" + nam.ToString();
            //dsThuNganVien = new DataSet();
            //dsThuNganVien = BaocaoNPC.common.GlobalServices.Service_NPCUS.select_ThuNganVien(strMa_dviqly);
            //if (dsThuNganVien != null) txtThuNganVien.AddItem(new CMIS2_TextBox.AutoCompleteEntry(dsThuNganVien));
            //txtThuNganVien.FocusAutoText();
        }

        private void UserControl_KeyDown(object sender, KeyEventArgs e)
        {

        }

        private void btnLaySoLieu_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (txtDuongDan.Text.Trim() == "")
                {
                    TootsNPC.ShowMessage.SetStatus("ERROR", this, btnLaySoLieu, "lblstatus", "Hãy chọn file excel");
                    dsCNfile.Tables["dsCNFileExcel"].Rows.Clear();
                    dgrHDON_CNO.ItemsSource = null;
                    return;
                }
                dt_ReadFileExcel = new DataTable();
                dt_ReadFileExcel = TootsNPC.compression.dsReadExcel(txtDuongDan.Text, 0);
                if (dt_ReadFileExcel.Rows.Count == 0)
                {
                    TootsNPC.ShowMessage.SetStatus("ERROR", this, btnLaySoLieu, "lblstatus", "file không có số liệu!");
                    dsCNfile.Tables["dsCNFileExcel"].Rows.Clear();
                    dgrHDON_CNO.ItemsSource = null;
                    return;
                }
                //DataTable dt = new DataTable();
                dsCNfile.Tables["dsCNFileExcel"].Rows.Clear();
                for (int i = 0; i < dt_ReadFileExcel.Rows.Count; i++)
                {
                    // lấy dòng check
                    if (dt_ReadFileExcel.Rows[i][0].ToString().Trim() != "")
                    {
                        check_cham = "CHECK";
                    }
                    else
                    { check_cham = "UNCHECK"; }
                        // tiếp tục kiểm tra dong mã khách hàng và id hóa đơn
                        if (dt_ReadFileExcel.Rows[i][2].ToString().Trim() != "" && dt_ReadFileExcel.Rows[i][4].ToString().Trim() != "")
                        {
                            if (TootsNPC.NPCNumber.numberic(dt_ReadFileExcel.Rows[i][4].ToString()))
                            {
                                Int64 id_hdon = Convert.ToInt64(dt_ReadFileExcel.Rows[i][4].ToString());
                                string ma_khang = dt_ReadFileExcel.Rows[i][2].ToString();
                                //DataSet ds = cls.SELECT_HOADON_FILE(strMa_dviqly, ma_khang, id_hdon,ref maloi);
                                DataSet ds = GlobalServices.Service_NPCUS.SELECT_HOADON_FILE(strMa_dviqly, ma_khang, id_hdon, check_cham, ref maloi);
                                if (ds != null || ds.Tables[0].Rows.Count > 0)
                                {
                                    TootsNPC.NPCDatasetTable.AddTable(ds.Tables[0], dsCNfile.Tables["dsCNFileExcel"]);
                                }
                            }
                        }
                }
                dgrHDON_CNO.ItemsSource = dsCNfile.Tables["dsCNFileExcel"].DefaultView;
                string thunganvien = dsCNfile.Tables["dsCNFileExcel"].Rows[0]["MA_TNGAN"].ToString() + " --- " + dsCNfile.Tables["dsCNFileExcel"].Rows[0]["TEN_TNGAN"].ToString();
                txtThuNganVien.Text = thunganvien;
                Decimal total = TootsNPC.NPCDatasetTable.SumColumnTable(dsCNfile.Tables["dsCNFileExcel"],"TONGTIEN");
                Decimal check = TootsNPC.NPCDatasetTable.SumCheckTable(dsCNfile.Tables["dsCNFileExcel"], "TONGTIEN", "True");
                //Decimal uncheck = TootsNPC.NPCDatasetTable.SumCheckTable(dsCNfile.Tables["dsCNFileExcel"], "TONGTIEN", "False");

                int countuncheck = TootsNPC.NPCDatasetTable.CountCheckTable(dsCNfile.Tables["dsCNFileExcel"],"CHON","False");
                int countcheck = TootsNPC.NPCDatasetTable.CountCheckTable(dsCNfile.Tables["dsCNFileExcel"], "CHON", "True");

                lblThongtin.Content = "Hóa đơn chấm: " + countcheck.ToString() + " - Tổng tiền: " + check.ToString("#,###,###,###") +
                                      " - Tổng hóa đơn: " + dsCNfile.Tables["dsCNFileExcel"].Rows.Count.ToString() + " - Tổng tiền: " + total.ToString("#,###,###,###");

            }
            catch (Exception ex)
            {
                TootsNPC.ShowMessage.SetStatus("ERROR",this,btnLaySoLieu,"lblstatus",ex.ToString());
            }
        }

        private void btnCapNhat_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // check ngay
                if (dtpNgayNOP.Text == string.Empty)
                {
                    TootsNPC.ShowMessage.SetStatus("ERROR", this, btnCapNhat, "lblstatus", "Hãy chọn ngày cập nhật số liệu!");
                    return;
                }
                string ERRO = "";
                int pcount = dsCNfile.Tables["dsCNFileExcel"].Select("CHAM = True").Count();
                int pcount1 = dsCNfile.Tables["dsCNFileExcel"].Rows.Count;
                if (pcount == 0)
                { TootsNPC.ShowMessage.SetStatus("ERROR",this,btnCapNhat,"lblstatus", "Không có hóa đơn nào được chọn chấm lần này"); return; }
                if (pcount1 == 0)
                { TootsNPC.ShowMessage.SetStatus("ERROR", this, btnCapNhat, "lblstatus", "Không có dữ liệu chấm nợ"); return; }

                if (MessageBox.Show("Bạn có muốn cập nhật chấm nợ cho " + pcount.ToString() + " hóa đơn không?", "Thông báo", MessageBoxButton.OKCancel, MessageBoxImage.Question) == MessageBoxResult.OK)
                {
                    // nhận số liệu vào off line
                    DataTable dt = dsCNfile.Tables["dsCNFileExcel"] as DataTable;
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        if (dt.Rows[i]["CHAM"].ToString() == "True")
                        {
                            ds_CAPNHAT.Tables["NPC_CHAMNO_OFFLINE"].Rows.Clear();
                            DataRow dr = ds_CAPNHAT.Tables["NPC_CHAMNO_OFFLINE"].NewRow();
                            //dr["ID_CAYLUOIDIEN"] = OMS_DANHMUC.Pglobal.strMa_dviqly;
                            dr["MA_DVIQLY"] = dt.Rows[i]["MA_DVIQLY"].ToString();
                            dr["MA_KHANG"] = dt.Rows[i]["MA_KHANG"].ToString();
                            dr["ID_HDON"] = Convert.ToInt64(dt.Rows[i]["ID_HDON"]);
                            dr["TIEN_NOP"] = Convert.ToDecimal(dt.Rows[i]["TIEN_NO"].ToString());
                            dr["THUE_NOP"] = Convert.ToDecimal(dt.Rows[i]["THUE_NO"].ToString());
                            dr["SO_BBGIAO"] = Convert.ToInt64(dt.Rows[i]["SO_BBGIAO"]);
                            dr["MA_TNGAN"] = dt.Rows[i]["MA_TNGAN"].ToString();
                            dr["MA_TNGAN_THUHO"] = dt.Rows[i]["MA_TNGAN"].ToString();
                            dr["NGAY_CHAMNO"] = dtpNgayNOP.SelectedDate.Value.Date;
                            dr["NAM_HT"] = nam;
                            dr["THANG_HT"] = thang;
                            dr["TRANGTHAI"] = 0;
                            dr["GROUP_NHOM"] = "";
                            dr["NGUOI_TAO"] = strTenDNHap;
                            dr["TINHTRANGIN"] = 0;
                            dr["NGAY_TAO"] = DateTime.Now;
                            ds_CAPNHAT.Tables["NPC_CHAMNO_OFFLINE"].Rows.Add(dr);
                            ds_CAPNHAT.AcceptChanges();
                            //if (!cls.insert_NPC_CHAMNO_OFFLINE(ds_CAPNHAT, ref maloi))
                            if (!GlobalServices.Service_NPCUS.insert_NPC_CHAMNO_OFFLINE(ds_CAPNHAT, ref maloi))
                            {
                                TootsNPC.ShowMessage.SetStatus("ERORR", this, btnCapNhat, "lblstatus", maloi);
                                return;
                            }
                            //Ghilog
                            ds_CAPNHAT.Tables["NPC_CHAMNO_OFFLINE_LOG"].Rows.Clear();
                            DataRow drlog = ds_CAPNHAT.Tables["NPC_CHAMNO_OFFLINE_LOG"].NewRow();
                            drlog["MA_DVIQLY"] = dt.Rows[i]["MA_DVIQLY"].ToString();
                            drlog["MA_KHANG"] = dt.Rows[i]["MA_KHANG"].ToString();
                            drlog["ID_HDON"] = Convert.ToInt64(dt.Rows[i]["ID_HDON"]);
                            drlog["SO_BBGIAO"] = Convert.ToInt64(dt.Rows[i]["SO_BBGIAO"]);
                            drlog["NAM_HT"] = nam;
                            drlog["THANG_HT"] = thang;
                            drlog["MA_TNGAN"] = dt.Rows[i]["MA_TNGAN"].ToString();
                            drlog["NGAY_CHAMNO"] = dtpNgayNOP.SelectedDate.Value.Date;
                            drlog["TRANGTHAI"] = 3;
                            drlog["NGUOI_TAO"] = strTenDNHap;
                            drlog["NGAY_TAO"] = DateTime.Now;
                            drlog["GIO"] = DateTime.Now.Hour;
                            ds_CAPNHAT.Tables["NPC_CHAMNO_OFFLINE_LOG"].Rows.Add(drlog);
                            ds_CAPNHAT.AcceptChanges();
                            if (!GlobalServices.Service_NPCUS.insert_NPC_CHAMNO_OFFLINE_LOG(ds_CAPNHAT, ref maloi))
                            {
                                TootsNPC.ShowMessage.SetStatus("ERORR", this, btnCapNhat, "lblstatus", maloi);
                                //chamno = false;
                            }
                        }
                    }
                    TootsNPC.ShowMessage.SetStatus("SUCCESS", this, btnCapNhat, "lblstatus", "Cập nhật số liệu thành công");
                }
            }
            catch(Exception ex)
            {
                TootsNPC.ShowMessage.SetStatus("ERORR", this, btnCapNhat, "lblstatus", ex.ToString());
            }
        }

        private void CHECK_CHAM_Click(object sender, RoutedEventArgs e)
        {

        }
    }
}
